import {defineStore} from "pinia";
import {type} from "../model/type";
import {RandomAvatar} from "../utils/utils";

export const userStore = defineStore('user', {
    state: () => {
        return {
            // 定义 状态数据
            userInfo: JSON.parse(sessionStorage.getItem('userInfo') as string) as type.Token || {
                token: '',
                user: {},
                orgs:[],
                roles:[],
                orgRole:[],
                role:-1,
                org:-1
            } as type.Token,
            center:JSON.parse(sessionStorage.getItem('userCenter') as string)||{
                // 个人中心 设置面板 tabs 活页选项卡
                activeName:'用户设置'
            }
        }
    },
    getters: {
        // 获取用户头像
        GetHeadImg():string{
            let picture = this.userInfo.user.picture;
            if (picture===''||picture===undefined){
                // 返回随机头像
                return RandomAvatar()
            }
            return picture
        }
    },
    actions: {
        UpdateToken(token: type.Token) {
            this.userInfo = token
            let value = JSON.stringify(token)
            sessionStorage.setItem("userInfo", value)
        },
        UpdateOrgAndRole(org:number,role:number){
            this.userInfo.org=org
            this.userInfo.role=role
            let value = JSON.stringify(this.userInfo)
            sessionStorage.setItem("userInfo",value )
        },
        SetActiveName(name :string){
            this.center.activeName=name
            let value = JSON.stringify( this.center)
            sessionStorage.setItem("userCenter",value)
        }
    }
})